/**
 * Created with IntelliJ IDEA.
 * User: "Balasubramanian"
 * Date: 8/10/13
 * Time: 12:06 PM
 * To change this template use File | Settings | File Templates.
 */

/*
--------------------------------------------------------------------------------------------------------------------

Utility functions is a collection of static methods that perform some common functions that may be required by any
of the modules in the application.
This class cannot be instantiated.
As of now, it has methods to create a file, to get a logger object and to clean up the logger object.

---------------------------------------------------------------------------------------------------------------------
 */

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.FileHandler;
import java.util.logging.Handler;


public class UtilityFunctions {

    private UtilityFunctions()
    {
        //This class cannot be instantiated
    }

    //Given the path of the file as a String, it creates the file if the same does not exist already
    static void createFile(String filePath)
    {
        File file=new File(filePath);
        try
        {
            if(!file.exists())
            {
                file.createNewFile();
            }
        }
        catch(IOException e)
        {
            System.out.println("Sorry, the system is experiencing faults. Please try again later");
            System.exit(1);
        }
    }

    // This function returns a java.util.logger object
    // It also creates the appropriate log file if it does not exist
    static Logger getLogger(String logFilePath,String logName)
    {
        Logger logger=Logger.getLogger(logName);
        logger.setLevel(Level.INFO);
        logger.setUseParentHandlers(false);

        try
        {
            FileHandler fh=new FileHandler(logFilePath,true);
            logger.addHandler(fh);
            fh.setFormatter(new SimpleFormatter());
        }
        catch(IOException e)
        {
            System.out.println("Sorry, the system is experiencing faults. Please try again later");
            System.exit(1);
        }

        createFile(logFilePath);

        return logger;

    }

    // Removes all the file handlers associated with the logger.
    // This helps in cleaning up the .lck files that get created by the logger object
    static void cleanUpLogger(Logger logger)
    {
        for(Handler h:logger.getHandlers())
        {
            h.flush();
            h.close();
        }
    }
}
